<template>
  <div class="query-container">
    <!-- 搜索框 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="用户名">
          <el-input v-model="formInline.username" style="width: 180px" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formInline.phone" style="width: 180px" placeholder="请输入电话" clearable />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="formInline.realName" style="width: 180px" placeholder="请输入真实姓名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <!-- 基本信息弹窗 -->
      <el-dialog v-model="dialogFormVisible" :title="dialogType==='add'?'添加':'修改'" width="900px" :close-on-click-modal="false" draggable>
        <el-form :model="userForm" ref="userFormRef" :rules="userFormRules" label-width="140px" :disabled="formLoading">
          <el-tabs v-model="activeFormTab">
            <!-- 基本信息选项卡 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username" >
                    <el-input v-model="userForm.username" placeholder="请输入用户名" autocomplete="off" :disabled="dialogType==='edit'" />
                    <div class="form-hint" v-if="dialogType==='add'">
                      用户名由5-10位字符组成，一旦创建不可修改，默认密码123456abc
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="真实姓名" prop="realName" >
                    <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="电话" prop="phone" >
                    <el-input v-model="userForm.phone" placeholder="请输入电话" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="sex" >
                    <el-radio-group v-model="userForm.sex">
                      <el-radio label="f" >女</el-radio>
                      <el-radio label="m" >男</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="民族" prop="nation">
                    <el-input v-model="userForm.nation" placeholder="请输入民族" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期" prop="birthDate">
                    <el-date-picker v-model="userForm.birthDate" type="date" placeholder="选择出生日期" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCard">
                    <el-input v-model="userForm.idCard" placeholder="请输入身份证号" maxlength="18" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="政治面貌" prop="politicalStatus">
                    <el-select v-model="userForm.politicalStatus" placeholder="请选择政治面貌">
                      <el-option label="中共党员" value="中共党员" />
                      <el-option label="中共预备党员" value="中共预备党员" />
                      <el-option label="群众" value="群众" />
                      <el-option label="共青团员" value="共青团员" />
                      <el-option label="民主党派" value="民主党派" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="入党时间" prop="partyDate" v-if="userForm.politicalStatus && userForm.politicalStatus.includes('党员')">
                    <el-date-picker v-model="userForm.partyDate" type="date" placeholder="选择入党时间" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="现居住地" prop="address">
                    <el-input v-model="userForm.address" placeholder="请输入现居住地" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="学历" prop="education">
                    <el-select v-model="userForm.education" placeholder="请选择学历">
                      <el-option label="博士" value="博士" />
                      <el-option label="硕士" value="硕士" />
                      <el-option label="本科" value="本科" />
                      <el-option label="大专" value="大专" />
                      <el-option label="高中" value="高中" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="状态" prop="flag">
                    <el-switch v-model="userForm.flag" inline-prompt active-text="开" inactive-text="关" :active-value="'0'" :inactive-value="'1'"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="角色" prop="roleId">
                    <el-select v-model="userForm.roleId" placeholder="请选择角色">
                      <el-option label="超级管理员" value="1" />
                      <el-option label="管理员" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="备注" prop="remark">
                <el-input v-model="userForm.remark" placeholder="请输入备注" :rows="3" type="textarea"/>
              </el-form-item>

              <el-form-item label="一寸照片">
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :on-change="handlePhotoUpload"
                  :show-file-list="false"
                  accept="image/jpeg,image/png"
                  :before-upload="beforePhotoUpload"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传蓝底一寸照片 (JPG/PNG格式，不超过2MB)</div>
                    <div v-if="userForm.photoPath" class="el-upload__tip">
                      已上传: {{ getFileName(userForm.photoPath) }}
                      <br>存储位置: {{ userForm.photoPath }}
                    </div>
                  </template>
                </el-upload>
                <!-- 照片预览 -->
                <div v-if="photoPreviewUrl" class="photo-preview">
                  <img :src="photoPreviewUrl" alt="照片预览" class="preview-img">
                  <el-button
                    type="text"
                    class="delete-preview"
                    @click="clearPhotoPreview"
                  >
                    <el-icon><Delete /></el-icon> 移除
                  </el-button>
                </div>
              </el-form-item>

              <el-form-item label="个人简历">
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :on-change="handleResumeUpload"
                  :show-file-list="false"
                  accept=".pdf,.doc,.docx"
                  :before-upload="beforeResumeUpload"
                >
                  <el-button type="primary">点击上传简历</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传个人简历（从大学开始，支持PDF、Word格式，不超过10MB）</div>
                    <div v-if="userForm.resumePath" class="el-upload__tip">
                      已上传: {{ getFileName(userForm.resumePath) }}
                      <br>存储位置: {{ userForm.resumePath }}
                      <el-button type="text" @click="downloadResume(userForm.resumePath)">
                        <el-icon><Download /></el-icon> 下载
                      </el-button>
                    </div>
                  </template>
                </el-upload>
                <!-- 简历文件信息 -->
                <div v-if="resumeFile" class="file-info">
                  待上传文件: {{ resumeFile.name }} ({{ formatFileSize(resumeFile.size) }})
                  <el-button
                    type="text"
                    class="delete-file"
                    @click="clearResumeFile"
                  >
                    <el-icon><Delete /></el-icon> 移除
                  </el-button>
                </div>
              </el-form-item>
            </el-tab-pane>

            <!-- 职业信息选项卡 -->
            <el-tab-pane label="职业信息" name="professional">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="毕业院校" prop="graduateSchool">
                    <el-input v-model="userForm.graduateSchool" placeholder="请输入毕业院校" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="专业" prop="major">
                    <el-input v-model="userForm.major" placeholder="请输入专业" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="执业证号" prop="practiceCertNo">
                    <el-input v-model="userForm.practiceCertNo" placeholder="请输入执业证号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="资格取得日期" prop="qualificationDate">
                    <el-date-picker v-model="userForm.qualificationDate" type="date" placeholder="选择资格取得日期" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="业务特长" prop="specialty">
                    <el-input v-model="userForm.specialty" placeholder="请输入业务特长" type="textarea" :rows="2" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否合伙人" prop="isPartner">
                    <el-radio-group v-model="userForm.isPartner">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="聘用日期" prop="hireDate">
                    <el-date-picker v-model="userForm.hireDate" type="date" placeholder="选择聘用日期" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="律师类型" prop="lawyerType">
                    <el-select v-model="userForm.lawyerType" placeholder="请选择律师类型">
                      <el-option label="专职律师" value="专职律师" />
                      <el-option label="兼职律师" value="兼职律师" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="兼职工作单位" prop="partTimeWorkUnit" v-if="userForm.lawyerType === '兼职律师'">
                    <el-input v-model="userForm.partTimeWorkUnit" placeholder="请输入兼职工作单位" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否人大代表/政协委员" prop="isDeputy">
                    <el-radio-group v-model="userForm.isDeputy">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <!-- 其他信息选项卡 -->
            <el-tab-pane label="其他信息" name="other">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="受过的奖励" prop="rewards">
                    <el-input v-model="userForm.rewards" placeholder="请输入受过的奖励" type="textarea" :rows="3" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="受过的处分" prop="punishments">
                    <el-input v-model="userForm.punishments" placeholder="请输入受过的处分" type="textarea" :rows="3" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="首次社保缴费日期" prop="socialSecurityDate">
                    <el-date-picker v-model="userForm.socialSecurityDate" type="date" placeholder="选择首次社保缴费日期" style="width: 100%" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="社保编号" prop="socialSecurityNo">
                    <el-input v-model="userForm.socialSecurityNo" placeholder="请输入社保编号" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="社会职务" prop="socialPosition">
                <el-input v-model="userForm.socialPosition" placeholder="请输入社会职务" type="textarea" :rows="2" />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm()" :loading="formLoading">
              {{dialogType==='add'?'添加':'修改'}}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 详细信息弹窗 -->
      <el-dialog v-model="detailDialogVisible" title="律师详细信息" width="1000px" :close-on-click-modal="false">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row>
              <el-col :span="8">
                <div class="photo-container" v-if="currentUser.photoPath">
                  <img :src="getPhotoUrl(currentUser.photoPath)" alt="一寸照片" class="user-photo" />
                  <div class="photo-label">一寸照片</div>
<!--                  <div class="file-path">存储位置: {{ currentUser.photoPath }}</div>-->
                </div>
                <div v-else class="no-photo">暂无照片</div>
              </el-col>
              <el-col :span="16">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
                  <el-descriptions-item label="真实姓名">{{ currentUser.realName }}</el-descriptions-item>
                  <el-descriptions-item label="电话">{{ currentUser.phone }}</el-descriptions-item>
                  <el-descriptions-item label="性别">{{ currentUser.sex === 'f' ? '女' : '男' }}</el-descriptions-item>
                  <el-descriptions-item label="民族">{{ currentUser.nation }}</el-descriptions-item>
                  <el-descriptions-item label="出生日期">{{ formatDate(currentUser.birthDate) }}</el-descriptions-item>
                  <el-descriptions-item label="身份证号">{{ currentUser.idCard }}</el-descriptions-item>
                  <el-descriptions-item label="政治面貌">{{ currentUser.politicalStatus }}</el-descriptions-item>
                  <el-descriptions-item label="入党时间">{{ formatDate(currentUser.partyDate) }}</el-descriptions-item>
                  <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
                  <el-descriptions-item label="现居住地">{{ currentUser.address }}</el-descriptions-item>
                  <el-descriptions-item label="学历">{{ currentUser.education }}</el-descriptions-item>
                  <el-descriptions-item label="状态">{{ currentUser.flag === '0' ? '正常' : '关闭' }}</el-descriptions-item>
                  <el-descriptions-item label="角色">{{ currentUser.roleName }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="职业信息" name="professional">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="毕业院校">{{ currentUser.graduateSchool || '-' }}</el-descriptions-item>
              <el-descriptions-item label="专业">{{ currentUser.major || '-' }}</el-descriptions-item>
              <el-descriptions-item label="执业证号">{{ currentUser.practiceCertNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="资格取得日期">{{ formatDate(currentUser.qualificationDate) }}</el-descriptions-item>
              <el-descriptions-item label="业务特长">{{ currentUser.specialty || '-' }}</el-descriptions-item>
              <el-descriptions-item label="是否合伙人">{{ currentUser.isPartner === '1' ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="聘用日期">{{ formatDate(currentUser.hireDate) }}</el-descriptions-item>
              <el-descriptions-item label="律师类型">{{ currentUser.lawyerType || '-' }}</el-descriptions-item>
              <el-descriptions-item label="兼职工作单位">{{ currentUser.partTimeWorkUnit || '-' }}</el-descriptions-item>
              <el-descriptions-item label="是否人大代表/政协委员">{{ currentUser.isDeputy === '1' ? '是' : '否' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="其他信息" name="other">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="受过的奖励">{{ currentUser.rewards || '无' }}</el-descriptions-item>
              <el-descriptions-item label="受过的处分">{{ currentUser.punishments || '无' }}</el-descriptions-item>
              <el-descriptions-item label="首次社保缴费日期">{{ formatDate(currentUser.socialSecurityDate) }}</el-descriptions-item>
              <el-descriptions-item label="社保编号">{{ currentUser.socialSecurityNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="社会职务">{{ currentUser.socialPosition || '无' }}</el-descriptions-item>
              <el-descriptions-item label="个人简历">
                <div v-if="currentUser.resumePath">
                  <span>文件: {{ getFileName(currentUser.resumePath) }}</span>
                  <br>
                  <span>存储位置: {{ currentUser.resumePath }}</span>
                  <br>
                  <el-button type="primary" size="small" @click="downloadResume(currentUser.resumePath)">
                    <el-icon><Download /></el-icon> 下载简历
                  </el-button>
                </div>
                <span v-else>无</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>

      <div class="table-header">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"  width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column property="username" label="用户名" width="120" />
        <el-table-column property="realName" label="真实姓名" width="120" />
        <el-table-column property="phone" label="电话" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="scope">{{ scope.row.sex=='f'?'女':scope.row.sex=='m'?'男':'' }}</template>
        </el-table-column>
        <el-table-column label="民族" width="80" prop="nation" />
        <el-table-column label="学历" width="80" prop="education" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.flag"
              inline-prompt
              active-text="开"
              inactive-text="关"
              :active-value="'0'"
              :inactive-value="'1'"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column property="roleName" label="角色" width="120" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)" :loading="scope.row.loading">
              修改
            </el-button>
            <el-button size="small" type="primary" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" :loading="scope.row.loading">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[2, 5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, onUnmounted, ref } from 'vue'
import type { FormInstance, TableInstance, UploadProps } from 'element-plus'
import { ElMessage, FormRules, ElMessageBox, ElIcon } from "element-plus";
import { Delete, Download } from '@element-plus/icons-vue'
import { addUser, deleteUser, editUser, fetchUsersBycondition } from "@/api/user";

// 定义本地备份路径
const backupLocation = "D:/project(xingmu)/img";

// 定义用户接口
interface User {
  id: string;
  username: string;
  realName: string;
  phone: string;
  sex: string;
  flag: string;
  roleId: string;
  remark: string;
  nation: string;
  birthDate: string | null;
  idCard: string;
  politicalStatus: string;
  partyDate: string | null;
  email: string;
  address: string;
  education: string;
  photoPath: string;
  resumePath: string;
  roleName: string;
  graduateSchool?: string;
  major?: string;
  practiceCertNo?: string;
  qualificationDate?: string | null;
  specialty?: string;
  isPartner?: string;
  hireDate?: string | null;
  lawyerType?: string;
  partTimeWorkUnit?: string;
  isDeputy?: string;
  rewards?: string;
  punishments?: string;
  socialSecurityDate?: string | null;
  socialSecurityNo?: string;
  socialPosition?: string;
  loading?: boolean; // 用于操作时的加载状态
}

// 文件上传相关
const photoFile = ref<File | null>(null)
const resumeFile = ref<File | null>(null)
const photoPreviewUrl = ref('')

// 处理照片上传
const handlePhotoUpload: UploadProps['onChange'] = (file) => {
  photoFile.value = file.raw as File;
  // 创建预览URL
  if (file.raw) {
    photoPreviewUrl.value = URL.createObjectURL(file.raw);
  }
};

// 处理简历上传
const handleResumeUpload: UploadProps['onChange'] = (file) => {
  resumeFile.value = file.raw as File;
};

// 清除照片预览
const clearPhotoPreview = () => {
  photoFile.value = null;
  if (photoPreviewUrl.value) {
    URL.revokeObjectURL(photoPreviewUrl.value);
    photoPreviewUrl.value = '';
  }
  // 如果是编辑状态，可以选择清除已上传的照片路径
  if (dialogType.value === 'edit') {
    userForm.photoPath = '';
  }
};

// 清除简历文件
const clearResumeFile = () => {
  resumeFile.value = null;
  // 如果是编辑状态，可以选择清除已上传的简历路径
  if (dialogType.value === 'edit') {
    userForm.resumePath = '';
  }
};

// 照片上传前校验
const beforePhotoUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
  }
  return isJpgOrPng && isLt2M;
};

// 简历上传前校验
const beforeResumeUpload = (file: File) => {
  const isDocOrPdf = file.type === 'application/pdf' ||
    file.type === 'application/msword' ||
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isDocOrPdf) {
    ElMessage.error('只能上传PDF、Word格式的文件');
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB');
  }
  return isDocOrPdf && isLt10M;
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 获取文件名（从路径中提取）
const getFileName = (path: string) => {
  if (!path) return '';
  // 处理Windows路径
  return path.substring(path.lastIndexOf('\\') + 1 || path.lastIndexOf('/') + 1);
};

// 组件卸载时释放URL
onUnmounted(() => {
  if (photoPreviewUrl.value) {
    URL.revokeObjectURL(photoPreviewUrl.value);
  }
});

// 详细信息弹窗相关
const detailDialogVisible = ref(false)
const activeTab = ref('basic')
const currentUser = reactive<User>({
  id: '',
  username: '',
  realName: '',
  phone: '',
  sex: '',
  flag: '',
  roleId: '',
  remark: '',
  nation: '',
  birthDate: null,
  idCard: '',
  politicalStatus: '',
  partyDate: null,
  email: '',
  address: '',
  education: '',
  photoPath: '',
  resumePath: '',
  roleName: ''
})

function handleViewDetail(row: User) {
  Object.assign(currentUser, row)
  detailDialogVisible.value = true
}

// 获取照片URL - 不依赖getFileUrl接口
function getPhotoUrl(photoPath: string) {
  if (!photoPath) {
    return '/src/assets/default-avatar.png';
  }

  if (photoPreviewUrl.value && dialogType.value === 'edit' && photoFile.value) {
    return photoPreviewUrl.value;
  }

  // 直接使用路径或默认图（不依赖getFileUrl接口）
  return photoPath.includes('http') ? photoPath : '/src/assets/default-avatar.png';
}

// 下载简历 - 不依赖getFileUrl接口
function downloadResume(resumePath: string) {
  if (!resumePath) {
    ElMessage.warning('没有可下载的简历文件');
    return;
  }

  try {
    // 尝试直接使用路径下载
    const fileName = getFileName(resumePath);

    // 检查路径是否是HTTP链接
    if (resumePath.includes('http')) {
      const link = document.createElement('a');
      link.href = resumePath;
      link.target = '_blank';
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success('文件开始下载');
    } else {
      // 本地路径，提示用户手动访问
      ElMessage.info(`文件存储位置: ${resumePath}\n请在文件管理器中访问该路径获取文件`);
    }
  } catch (error) {
    ElMessage.error('下载失败，请手动访问文件位置获取文件');
    console.error('下载错误:', error);
  }
}

/*添加和修改*/
const userForm = reactive({
  id: '',
  username: '',
  realName: '',
  phone: '',
  sex: 'f',
  flag: '0',
  roleId: '',
  remark: '',
  nation: '',
  birthDate: null as string | null,
  idCard: '',
  politicalStatus: '',
  partyDate: null as string | null,
  email: '',
  address: '',
  education: '',
  photoPath: '',
  resumePath: '',
  graduateSchool: '',
  major: '',
  practiceCertNo: '',
  qualificationDate: null as string | null,
  specialty: '',
  isPartner: '0',
  hireDate: null as string | null,
  lawyerType: '专职律师',
  partTimeWorkUnit: '',
  isDeputy: '0',
  rewards: '',
  punishments: '',
  socialSecurityDate: null as string | null,
  socialSecurityNo: '',
  socialPosition: ''
})

const userFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const formLoading = ref(false)
const dialogType = ref<'add'|'edit'>('add')
const activeFormTab = ref('basic')

function handleAdd() {
  dialogType.value = 'add'
  if (userFormRef.value) userFormRef.value.resetFields()
  Object.assign(userForm, {
    id: '',
    username: '',
    realName: '',
    phone: '',
    sex: 'f',
    flag: '0',
    roleId: '',
    remark: '',
    nation: '',
    birthDate: null,
    idCard: '',
    politicalStatus: '',
    partyDate: null,
    email: '',
    address: '',
    education: '',
    photoPath: '',
    resumePath: '',
    graduateSchool: '',
    major: '',
    practiceCertNo: '',
    qualificationDate: null,
    specialty: '',
    isPartner: '0',
    hireDate: null,
    lawyerType: '专职律师',
    partTimeWorkUnit: '',
    isDeputy: '0',
    rewards: '',
    punishments: '',
    socialSecurityDate: null,
    socialSecurityNo: '',
    socialPosition: ''
  })
  clearPhotoPreview()
  clearResumeFile()
  activeFormTab.value = 'basic'
  dialogFormVisible.value = true
}

function handleEdit(index: number, row: User) {
  dialogType.value = 'edit'
  if (userFormRef.value) userFormRef.value.resetFields()
  // 深拷贝，避免直接修改表格数据
  Object.assign(userForm, JSON.parse(JSON.stringify(row)))
  clearPhotoPreview()
  clearResumeFile()
  // 设置已上传照片的预览（不依赖getFileUrl接口）
  if (row.photoPath) {
    // 对于已上传的照片，创建一个空的Blob URL作为预览占位
    photoPreviewUrl.value = row.photoPath.includes('http') ? row.photoPath : URL.createObjectURL(new Blob());
  }
  activeFormTab.value = 'basic'
  dialogFormVisible.value = true
}

// 提交表单
function submitForm() {
  if (!userFormRef.value) return

  userFormRef.value.validate((valid) => {
    if (!valid) return
    formLoading.value = true

    // 创建 FormData 对象来处理文件上传
    const formData = new FormData()

    // 格式化日期字段
    const dateFields = ['birthDate', 'qualificationDate', 'hireDate', 'socialSecurityDate', 'partyDate']

    // 添加所有表单字段
    Object.keys(userForm).forEach(key => {
      let value = (userForm as any)[key]

      // 处理日期字段
      if (dateFields.includes(key) && value) {
        // 确保日期格式为 'yyyy-MM-dd'
        const date = new Date(value)
        value = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      }

      if (value !== null && value !== undefined && value !== '') {
        formData.append(key, value)
      }
    })

    // 添加文件
    if (photoFile.value) {
      formData.append('photoFile', photoFile.value)
      // 添加备份路径信息
      formData.append('backupLocation', backupLocation)
    }
    if (resumeFile.value) {
      formData.append('resumeFile', resumeFile.value)
      // 添加备份路径信息
      formData.append('backupLocation', backupLocation)
    }

    const request = dialogType.value === 'add' ? addUser : editUser
    request(formData).then(res => {
      ElMessage.success(res.msg || (dialogType.value === 'add' ? '添加成功' : '修改成功'))
      dialogFormVisible.value = false
      getUsersBycondition()
    }).catch(error => {
      // 处理后端返回的错误信息
      const errorMsg = error.response?.data?.msg || (dialogType.value === 'add' ? '添加失败' : '修改失败')
      ElMessage.error(errorMsg)
    }).finally(() => {
      formLoading.value = false
    })
  })
}

// 日期格式化函数
const formatDate = (date: string | null | undefined) => {
  if (!date) return '-'
  try {
    return new Date(date).toLocaleDateString()
  } catch (e) {
    return '-'
  }
}

// 删除相关函数
function confirmDelete(ids: string[]) {
  ElMessageBox.confirm(
    '请您确认是否删除选中的记录?',
    '消息',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 显示加载状态
      tableData.value.forEach(row => {
        if (ids.includes(row.id)) {
          row.loading = true
        }
      })

      await deleteUser(ids)
      ElMessage.success('删除成功')
      pagination.current = 1
      getUsersBycondition()
    } catch (error) {
      const errorMsg = error.response?.data?.msg || '删除失败'
      ElMessage.error(errorMsg)
    } finally {
      // 隐藏加载状态
      tableData.value.forEach(row => {
        if (ids.includes(row.id)) {
          row.loading = false
        }
      })
    }
  }).catch(() => {
    ElMessage.info('删除取消')
  })
}

function handleDelete(row: User) {
  confirmDelete([row.id])
}

function handleBatchDelete() {
  if (multipleSelection.value.length > 0) {
    const ids = multipleSelection.value.map(item => item.id)
    confirmDelete(ids)
  } else {
    ElMessage.error("请选择要删除的数据")
  }
}

// 状态变更处理
function handleStatusChange(row: User) {
  // 创建临时对象用于更新
  const tempUser = {
    id: row.id,
    flag: row.flag,
    // 复制其他必要字段，避免更新时丢失数据
    username: row.username,
    realName: row.realName,
    phone: row.phone,
    sex: row.sex,
    roleId: row.roleId
  }

  row.loading = true
  // 创建FormData并添加数据
  const formData = new FormData()
  Object.keys(tempUser).forEach(key => {
    formData.append(key, (tempUser as any)[key])
  })

  editUser(formData).then(() => {
    ElMessage.success('状态更新成功')
  }).catch(error => {
    // 失败时回滚状态
    row.flag = row.flag === '0' ? '1' : '0'
    ElMessage.error('状态更新失败: ' + (error.response?.data?.msg || error.message))
  }).finally(() => {
    row.loading = false
  })
}

// 搜索相关
const formInline = reactive({
  username: '',
  phone: '',
  realName: '',
})

const onSubmit = () => {
  pagination.current = 1
  getUsersBycondition()
}

function resetForm() {
  formInline.username = ""
  formInline.phone = ""
  formInline.realName = ""
  pagination.current = 1
  getUsersBycondition()
}

// 表格相关
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}

const tableData = ref<User[]>([])

function getUsersBycondition() {
  const params = {
    ...formInline,
    page: pagination.current,
    pageSize: pagination.pageSize
  }
  fetchUsersBycondition(params).then(res => {
    tableData.value = res.data.list || []
    pagination.total = res.data.total || 0
  }).catch(e => {
    ElMessage.error("查询失败: " + (e.response?.data?.msg || e.message))
  })
}

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.current = 1
  getUsersBycondition()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  getUsersBycondition()
}

// 表单验证规则，与后端验证对应
const userFormRules = reactive<FormRules>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名的长度是5-10位', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  nation: [
    { required: true, message: '请输入民族', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  politicalStatus: [
    { required: true, message: '请选择政治面貌', trigger: 'change' }
  ],
  education: [
    { required: true, message: '请选择学历', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  graduateSchool: [
    { required: true, message: '请输入毕业院校', trigger: 'blur' }
  ],
  practiceCertNo: [
    { required: true, message: '请输入执业证号', trigger: 'blur' }
  ],
  qualificationDate: [
    { required: true, message: '资格取得日期不能为空', trigger: 'change' }
  ],
  hireDate: [
    { required: true, message: '请选择聘用日期', trigger: 'change' }
  ],
  lawyerType: [
    { required: true, message: '请选择律师类型', trigger: 'change' }
  ]
})

onMounted(() => {
  getUsersBycondition()
})
</script>

<style scoped>
.query-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}
.filter-card {
  border-radius: 10px;
  margin-bottom: 16px;
}
.table-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}
.form-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
:deep(.el-descriptions__body) {
  background-color: #fafafa;
}
:deep(.el-descriptions__label) {
  font-weight: bold;
}
.photo-container {
  text-align: center;
  margin-bottom: 20px;
}
.user-photo {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.photo-label {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}
.file-path {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
  word-break: break-all;
}
.no-photo {
  text-align: center;
  color: #999;
  padding: 60px 0;
  border: 1px dashed #ddd;
  border-radius: 4px;
}
.photo-preview {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.preview-img {
  max-width: 200px;
  max-height: 200px;
  border: 1px solid #eee;
  border-radius: 4px;
}
.file-info {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 10px;
}
.delete-preview, .delete-file {
  color: #ff4d4f;
  padding: 0;
  height: auto;
}
.delete-preview:hover, .delete-file:hover {
  color: #d93025;
}
</style>
